package com.onetech.adrewards.free.apicall;

import static jp.co.CAReward_Media.CARMIntent.LOGTAG;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jp.co.CAReward_Ack.CARAck;
import jp.co.CAReward_Ack.CARAckGetHttp;
import jp.co.CAReward_Ack.CARController;
import jp.co.CAReward_Media.CARMCommon;
import jp.co.CAReward_Media.CARMIntentInterface;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

public class ZuZuCARMApiCall extends AsyncTask<Void, Void, Void> {

	//private final int mWC = ViewGroup.LayoutParams.WRAP_CONTENT;
	
	private String mid;
	private String apiKey;
	private String userId;
	private final String apiUrl = "http://api.ca-reward.jp/reward/newapi/api_recommend/ApiRecommend.php?m_id=%s&api_key=%s&user_id=%s";
	private String wallUrl;
	private String mediaOwnerId;
	private String platformId = "3";
	private String appKey;
	private String loadingMsg;
	private String timeout = "10000";
	private Context context;
	//private RelativeLayout linearLayout;
	private ZuZuCARMWebView mCARMWebView;
	private View progressBar;
	
	/* ターゲティング関連 */
	private String targetApiResponse;
	private String targetUrlPrm = "";
	private final String RET_APP_EXIST = "1";			// 端末内にアプリが存在する場合の返却値
	private final String RET_APP_NOT_EXIST = "0";		// 端末内にアプリが存在しない場合の返却値
	
	public ZuZuCARMApiCall(Intent intent, Context context, ZuZuCARMWebView mCARMWebView, View _progressBar) {
		
		this.setInitPrm(intent);
		this.context = context;
		//this.linearLayout = linearLayout;
		this.mCARMWebView = mCARMWebView;
		this.progressBar = _progressBar;
	}
	
	private void setInitPrm(Intent intent) {
		
		this.wallUrl = intent.getStringExtra("url");
		this.mid = intent.getStringExtra("m_id");
		this.mediaOwnerId = intent.getStringExtra("m_owner_id");
		this.userId = intent.getStringExtra("user_id");
		this.apiKey = intent.getStringExtra("api_key");
		this.appKey = intent.getStringExtra("app_key");
		this.loadingMsg = intent.getStringExtra("loading_msg");
		String tmpTimeout = intent.getStringExtra("timeout");
		if(null != tmpTimeout) {
			this.timeout = tmpTimeout;
		}
	}
	
	private boolean callTargetApi() {
		
		String reqUrl = String.format(this.apiUrl, this.mid, this.apiKey, this.userId);
		CARAckGetHttp carHttp = new CARAckGetHttp();
		boolean errFlg = false;
		
		try{
			Log.d(LOGTAG, "API_URL:" + reqUrl);
			carHttp.setUrl(reqUrl);
			carHttp.setHttpConnection(5000);
			carHttp.isResponseOk();
			targetApiResponse = carHttp.getContent();
			Log.d(LOGTAG, "API-RESPONSE:" + targetApiResponse);
			if(targetApiResponse.indexOf("[ERR]") != -1) {
				errFlg = true;
				Log.d(LOGTAG, "API_ERROR:" + targetApiResponse);
			}
			if("".equals(targetApiResponse)) {
				errFlg = true;
				Log.d(LOGTAG, "api response is blank");
			}
		} catch(Exception e) {
			errFlg = true;
			// ログ出力
			Log.d(LOGTAG, "API CALL ERROR:" + e.toString());
		}
		return errFlg;
	}
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		switchViewLayout(false,true);
	}

	private void switchViewLayout(boolean isShowWebView,boolean isShowProgressBar) {
		mCARMWebView.setVisibility((isShowWebView?View.VISIBLE:View.GONE));
		progressBar.setVisibility((isShowProgressBar?View.VISIBLE:View.GONE));
	}
	@Override
	protected Void doInBackground(Void... params) {
		
		if(this.callTargetApi()) {
			return null;
		}
		
		try{
			this.convertResponse();
		}catch(Exception e) {
			Log.d(LOGTAG, "API_RESPONSE_ERROR:" + e.toString());
			Log.d(LOGTAG, "API_RESPONSE:" + targetApiResponse);
		}
		
		return null;
	}
	
	private void convertResponse() {
		
		String[] resParam = this.targetApiResponse.split("\\|");
		String[] urlSchemes = resParam[0].split(",");
		List<String> cids = new ArrayList<String>(Arrays.asList(resParam[1].split(",")));
		List<String> exists = new ArrayList<String>(cids.size());
		
		if(urlSchemes.length != cids.size()) {
			throw new RuntimeException("not equal count:" + this.targetApiResponse);
		}
		
		for(int i=0; i<urlSchemes.length; i++) {
			if(this.isInstalled(urlSchemes[i])){
				exists.add(this.RET_APP_EXIST);
			}else{
				exists.add(this.RET_APP_NOT_EXIST);
			}
		}
		
		this.targetUrlPrm = "&target_cid=" + this.convertListToString(cids, ",");
		this.targetUrlPrm += "&target_exist=" + this.convertListToString(exists, ",");
	}
	
	private String convertListToString(List<String> params, String delimiter) {
		
		String ret = "";
		
		for(int i=0; i<params.size(); i++) {
			if(i != 0) {
				ret += ",";
			}
			ret += params.get(i);
		}
		
		return ret;
	}
	
	private boolean isInstalled(String urlScheme) {
		
		PackageManager pm = this.context.getPackageManager();
		Intent intent = null;
		boolean installFlg = false;
		
		intent = new Intent(Intent.ACTION_VIEW);
		Uri uri = Uri.parse(urlScheme);
		intent.setData(uri);
		if(pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size() != 0) {
			installFlg = true;
		}
		
		return installFlg;
	}
	
	@Override
	protected void onPostExecute(Void params) {
		boolean usePointManager = CARController.upm_prms._usePointManage != 0?true:false;
		String  onetimeKey		= CARController.upm_prms._onetime_key;
		
		try{
			progressBar.setVisibility(View.GONE);
			// ポイント管理を利用する場合
			// フラグ、デリゲート、WebView を追加で設定
			mCARMWebView.init((Activity)this.context, this.getWallRequestUrl(usePointManager, onetimeKey), 
					this.loadingMsg, this.mid, this.mediaOwnerId, this.userId, this.platformId, this.apiKey, this.appKey, this.timeout, usePointManager,progressBar);
			mCARMWebView.addJavascriptInterface(new CARMIntentInterface(
					this.context, this.apiKey, this.userId, this.mid, this.timeout, this.appKey, this.mediaOwnerId, this.platformId,
					CARController.upm_prms._callback,
					this.mCARMWebView), 
					"CARMIntentInterface");
			// 
			//linearLayout.addView(mCARMWebView, createParam(mWC, mWC));
			switchViewLayout(true, false);
		}catch(Exception e){
			Log.d("CAR-API-CALL", "WEB-VIEW-ERR:" + e.toString());
		}
	}
	
	private String getWallRequestUrl(boolean usePointManager, String onetimeKey) {
		String url = "";
		
		if (this.wallUrl.indexOf("?") != -1) {
			url = this.wallUrl + "&user_id=";
		} else {
			url = this.wallUrl + "?user_id=";
		}

		url += this.userId;
		url += "&crypt=" + this.getCrypt();
		
		url += this.targetUrlPrm;
		
		url += CARAck.URLVERSION;
		
		// ポイント管理専用パラメータ
		if (usePointManager == true){
			url += "&gaid=" + onetimeKey;
		}
		Log.d(LOGTAG, "WALL_URL:" + url);
		
		return url;
	}
	
	private String getCrypt() {
		
		CARMCommon common = new CARMCommon();
		String crypt = null;
		
		try {
			crypt = common.encodeSHA1(this.userId + this.apiKey);
		} catch (Exception e) {
			Log.d(LOGTAG, "crypt failre");
			crypt = "";
		}
		
		return crypt;
	}
	
//	private LinearLayout.LayoutParams createParam(int w, int h) {
//		return new LinearLayout.LayoutParams(w, h);
//	}
}
